package com.afs.electronicforensics.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.afs.electronicforensics.activity.AudioCropActivity;
import com.afs.electronicforensics.activity.RecordActivity;
import com.hhmd.videocrop.VideoCropActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

;


public class MediaUtil
{

    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    // 录音类
    public static boolean imageFlag;
    public static Uri URI;
    public static String PATH;

    private static String[] PERMISSIONS_CAMERA = {
            Manifest.permission.CAMERA,
    };

    private static String[] PERMISSIONS_VIDEO = {
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
    };

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
    };

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        System.out.println("检测权限有没有"+permission);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            //动态获取权限
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    public static void verifyCameraPermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.CAMERA);
        System.out.println("检测拍照权限有没有"+permission);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            //动态获取权限
            ActivityCompat.requestPermissions(activity,PERMISSIONS_CAMERA ,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    public static void verifyVideoPermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.RECORD_AUDIO);
        System.out.println("检测录像权限有没有"+permission);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            //动态获取权限
            ActivityCompat.requestPermissions(activity,PERMISSIONS_VIDEO ,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    public static void openCameraForImage(Activity activity)
    {
        //检查是否有相机权限
        verifyCameraPermissions(activity);

        String draftPath = FileUtil.setOutPutPath(activity,Constants.USER_PATH.getDraftPath());

        File outputImage=new File(draftPath,"draft_image.jpg");
        try {
            if (outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT>=24){
            URI = FileProvider.getUriForFile(activity,"com.afs.fileprovider",outputImage);
        }else {
            URI =Uri.fromFile(outputImage);
        }
        Intent intent= new Intent("android.media.action.IMAGE_CAPTURE");
        // 仅当设置了MediaStore.EXTRA_OUTPUT参数时,系统将不再返回缩略图,而是会被完整保存以下路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, URI);
        activity.startActivityForResult(intent,
                Constants.FLAG_REQUEST_CAMERA_IMAGE);
    }

    public static void openCameraForVideo(Activity activity)
    {
        //检查是否有拍摄权限
        verifyVideoPermissions(activity);

        String draftPath = FileUtil.setOutPutPath(activity,Constants.USER_PATH.getDraftPath());
        String name = "draft_video.mp4";
        PATH = draftPath + name;
        File outputVideo=new File(draftPath,name);
        try {
            if (outputVideo.exists()){
                outputVideo.delete();
            }
            outputVideo.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT>=24){
            URI = FileProvider.getUriForFile(activity,"com.afs.fileprovider",outputVideo);
        }else {
            URI =Uri.fromFile(outputVideo);
        }
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, URI);
        activity.startActivityForResult(intent,
                Constants.FLAG_REQUEST_CAMERA_VIDEO);
    }

    public static void openAudioRecordForAudio(Activity activity)
    {
        //检查是否有录音机权限
        String outputPath = Environment.getExternalStorageDirectory().getAbsolutePath()+Constants.USER_PATH.getDraftPath();
        activity.startActivityForResult(RecordActivity.createIntent(activity,outputPath), Constants.FLAG_REQUEST_RECORD_AUDIO);

    }

    public static void pickImageFromSystem(Activity activity)
    {
        verifyStoragePermissions(activity);   //在这里手动获取权限   我不知道是我真机MIUI12的问题还是所有android6上下  和android10上下都有

        Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activity.startActivityForResult(intent,
                Constants.FLAG_REQUEST_SYSTEM_IMAGE);
    }


    public static void pickVideoFromSystem(Activity activity)
    {
        verifyStoragePermissions(activity);   //在这里手动获取权限   我不知道是我真机MIUI12的问题还是所有android6上下  和android10上下都有

        Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        activity.startActivityForResult(intent,
                Constants.FLAG_REQUEST_SYSTEM_VIDEO);
    }

    public static void pickAudioFromSystem(Activity activity)
    {
        verifyStoragePermissions(activity);   //在这里手动获取权限   我不知道是我真机MIUI12的问题还是所有android6上下  和android10上下都有

        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        activity.startActivityForResult(intent,
                Constants.FLAG_REQUEST_SYSTEM_AUDIO);
    }

    public static String getImagePathFromSystem(Activity activity, Intent data)
    {

        // TODO 处理从相册返回的数据
        Uri uri = data.getData();// 使用getData方法获取要调用的接口
        // 第二个参数表示要查询的数据的字段名
        Cursor c = activity.getContentResolver().query(uri,
                new String[]{MediaStore.Images.Media.DATA}, null, null, null);
        if (c != null)
        {
            c.moveToFirst();
            // 通过游标来获取名为MediaStore.Images.Media.DATA字段的值
            String path = c.getString(c
                    .getColumnIndex(MediaStore.Images.Media.DATA));
            return path;
        }
        return null;
    }

    public static String getVideoPathFromSystem(Activity activity, Intent data)
    {

        // TODO 处理从相册返回的数据
        Uri uri = data.getData();// 使用getData方法获取要调用的接口
        // 第二个参数表示要查询的数据的字段名
        Cursor c = activity.getContentResolver().query(uri,
                new String[]{MediaStore.Images.Media.DATA}, null, null, null);
        if (c != null)
        {
            c.moveToFirst();
            // 通过游标来获取名为MediaStore.Images.Media.DATA字段的值
            String path = c.getString(c
                    .getColumnIndex(MediaStore.Video.Media.DATA));
            return path;
        }
        return null;
    }

    public static String getAudioPathFromSystem(Activity activity, Intent data)
    {
        // TODO 处理从音乐返回的录音数据
        Uri uri = data.getData();// 使用getData方法获取要调用的接口
        // 第二个参数表示要查询的数据的字段名
        Cursor c = activity.getContentResolver().query(uri,
                new String[]{MediaStore.Audio.Media.DATA}, null, null, null);
        if (c != null)
        {
            c.moveToFirst();
            // 通过游标来获取名为MediaStore.Audio.Media.DATA字段的值
            String path = c.getString(c
                    .getColumnIndex(MediaStore.Audio.Media.DATA));
            return path;
        }
        return null;
    }


    /**
     * 调用系统的图片裁剪
     */
    public static void cropPhoto(Uri uri,Activity activity,boolean status) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //找到指定URI对应的资源图片
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        Bitmap bitmap = null;//图片Bitmap
        try {
            bitmap = BitmapFactory.
                    decodeStream(activity.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        System.out.println(width+","+height);

        // aspectX aspectY 是裁剪框宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1.5);
        intent.putExtra("outputX", width);// 输出图片大小
        intent.putExtra("outputY", height);

        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//发送裁剪信号，去掉也能进行裁剪
        intent.putExtra("scale", true);// 设置缩放
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        String path;
        String name;
        if(status){
            path = FileUtil.setOutPutPath(activity,Constants.USER_PATH.getImagePath());
            name = FileUtil.setPath(1);
        }else{
            path = FileUtil.setOutPutPath(activity,Constants.USER_PATH.getAvatarPath());
            name = FileUtil.setPath(4);
        }
        PATH = path + name;
        URI = Uri.fromFile(new File(PATH));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, URI);
        //进入系统裁剪图片的界面
        activity.startActivityForResult(intent, Constants.FLAG_REQUEST_CROP_IMAGE);
    }
    /**
     * 调用视频裁剪
     */
    public static void cropVideo(Activity activity,String inputPath) {
        String outputPath = FileUtil.setOutPutPath(activity,Constants.USER_PATH.getVideoPath());
        String outputVideo = outputPath + FileUtil.setPath(2);
        System.out.println(outputPath);
        activity.startActivityForResult(VideoCropActivity.createIntent(activity,inputPath,outputVideo), Constants.FLAG_REQUEST_CROP_VIDEO);
    }

    /**
     * 调用音频裁剪
     */
    public static void cropAudio(Activity activity, String inputPath) {
        String outputPath = FileUtil.setOutPutPath(activity, Constants.USER_PATH.getAudioPath());
        String outputAudio = outputPath + FileUtil.setPath(3);
        System.out.println(outputPath);
        activity.startActivityForResult(AudioCropActivity.createIntent(activity,inputPath,outputAudio), Constants.FLAG_REQUEST_CROP_AUDIO);
    }



    //保存图片
    public static void setPicToView(Bitmap mBitmap,Activity activity) {

        System.out.println("保存中。。。");
        verifyStoragePermissions(activity);
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd卡是否可用
            return;
        }
        FileOutputStream b = null;
        String path = activity.getExternalCacheDir()+ Constants.USER_PATH.getImagePath();
        File file = new File(path);
        file.mkdirs();// 创建以此File对象为名（path）的文件夹
        String fileName = path + FileUtil.setPath(1);//图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件（compress：压缩）

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
